package com.qk.management.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessPageDTO;
import com.qk.dto.business.BusinessPoolPageDTO;
import com.qk.dto.business.UpdateBusinessInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessTrackVO;
import com.qk.vo.business.BusinessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *
 *
 * @author blusr
 * @version 1.0
 * @date 2025/10/11 20:26
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    @Autowired
    private CustomerMapper customerMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void toCustomer(Integer id) {
        Business business = businessMapper.selectById(id);
        if (Objects.isNull(business)) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        business.setStatus(BusinessStatusConstants.BUSINESS_STATUS_CUSTOMER);
        business.setUpdateTime(LocalDateTime.now());
        businessMapper.updateById(business);

        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setId(null);
        customer.setBusinessId(business.getId());
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customerMapper.insert(customer);
    }

    @Override
    public PageResult<Business> getPoolPage(BusinessPoolPageDTO dto) {
        Page<Business> businessPage = page(new Page<>(dto.getPage(), dto.getPageSize()), Wrappers.lambdaQuery(Business.class)
                .eq(ObjectUtil.isNotEmpty(dto.getBusinessId()), Business::getId, dto.getBusinessId())
                .eq(ObjectUtil.isNotEmpty(dto.getSubject()), Business::getSubject, dto.getSubject())
                .like(ObjectUtil.isNotEmpty(dto.getName()) && !ObjectUtil.equals(dto.getName(), ""), Business::getName, dto.getName())
                .like(ObjectUtil.isNotEmpty(dto.getPhone()) && !ObjectUtil.equals(dto.getPhone(), ""), Business::getPhone, dto.getPhone())
                .eq(Business::getStatus, BusinessStatusConstants.BUSINESS_STATUS_RECYCLED)
                .orderByDesc(Business::getUpdateTime));
        return PageResult.<Business>builder()
                .total(businessPage.getTotal())
                .rows(businessPage.getRecords())
                .build();
    }

    @Override
    public PageResult<BusinessVO> page(BusinessPageDTO businessDTO) {
        Page<Business> businessPage = page(new Page<>(businessDTO.getPage(), businessDTO.getPageSize()), Wrappers.lambdaQuery(Business.class)
                .like(Objects.nonNull(businessDTO.getName()) && !Objects.equals(businessDTO.getName(), ""), Business::getName, businessDTO.getName())
                .eq(Objects.nonNull(businessDTO.getStatus()), Business::getStatus, businessDTO.getStatus())
                .eq(Objects.nonNull(businessDTO.getBusinessId()), Business::getId, businessDTO.getBusinessId())
                .like(Objects.nonNull(businessDTO.getPhone()) && !Objects.equals(businessDTO.getPhone(), ""), Business::getPhone, businessDTO.getPhone())
                .notIn(Business::getStatus, List.of(BusinessStatusConstants.BUSINESS_STATUS_RECYCLED, BusinessStatusConstants.BUSINESS_STATUS_CUSTOMER))
                .eqSql(Objects.nonNull(businessDTO.getAssignName()) && !Objects.equals(businessDTO.getAssignName(), ""), Business::getUserId, "SELECT id FROM t_user WHERE name LIKE " + "'%" + businessDTO.getAssignName() + "%'")
                .orderByDesc(Business::getUpdateTime));
        List<BusinessVO> businessVoList = businessPage.getRecords().stream().map(business -> {
            BusinessVO businessVo = BeanUtil.copyProperties(business, BusinessVO.class);
            businessVo.setAssignName(Objects.nonNull(userMapper.selectById(business.getUserId())) ? userMapper.selectById(business.getUserId()).getName() : "");
            return businessVo;
        }).collect(Collectors.toList());

        log.info("businessVoList:{}", businessVoList);
        return PageResult.<BusinessVO>builder()
                .total(businessPage.getTotal())
                .rows(businessVoList).build();
    }

    @Override
    public void addBusiness(BusinessDTO dto) {
        if (Objects.equals(dto.getName(), "") || Objects.isNull(dto.getName()) || Objects.equals(dto.getPhone(), "") || Objects.isNull(dto.getPhone()) || dto.getPhone().length() > 11) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setStatus(BusinessStatusConstants.BUSINESS_STATUS_UNASSIGNED);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        businessMapper.insert(business);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BusinessTrackVO getBusinessById(Integer id) {
        Business business = businessMapper.selectById(id);
        BusinessTrackVO businessTrackVO = BeanUtil.copyProperties(business, BusinessTrackVO.class);
        List<BusinessTrackVO.BusinessTrackRecordVO> collect = businessTrackRecordMapper
                .selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                .eq(BusinessTrackRecord::getBusinessId, id))
                .stream().map(record -> BeanUtil.copyProperties(record, BusinessTrackVO.BusinessTrackRecordVO.class)).collect(Collectors.toList());
        collect.forEach(record -> record.setAssignName(Objects.nonNull(userMapper.selectById(business.getUserId())) ? userMapper.selectById(business.getUserId()).getName() : ""));
        businessTrackVO.setTrackRecords(collect);
        return businessTrackVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBusinessInfo(UpdateBusinessInfoDTO dto) {
        if(dto.getNextTime().isBefore(LocalDateTime.now())){
            CommonException.throwCommonException(ParamEnum.NEXT_TIME_ERROR);
        }
        if(Objects.isNull(dto.getTrackStatus()) || Objects.isNull(dto.getKeyItems()) || Objects.isNull(dto.getNextTime()) || Objects.isNull(dto.getRecord())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setStatus(BusinessStatusConstants.BUSINESS_STATUS_FOLLOWING);
        business.setUpdateTime(LocalDateTime.now());
        businessMapper.updateById(business);

        BusinessTrackRecord record = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        record.setId(null);
        record.setBusinessId(dto.getId());
        record.setUserId(CurrentUserContextHolders.getUserId());
        record.setCreateTime(LocalDateTime.now());
        businessTrackRecordMapper.insert(record);
    }
}
